package com.insist.framework;

import com.insist.entity.UserInfo;
import com.insist.service.UserService;
import com.insist.util.MD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by INSIST on 2016/6/25.
 */
public class CmmRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) getAvailablePrincipal(principals);
        //通过用户名去获得用户的所有资源，并把资源存入info中
        //当然这里通常会操作数据库去获取
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> s = new HashSet<String>();
        s.add("p1");
        s.add("p2");
        info.setStringPermissions(s);
        Set<String> r = new HashSet<String>();
        r.add("r1");
        r.add("r2");
        info.setRoles(r);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //token中储存着输入的用户名和密码
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        char[] password = upToken.getPassword();
        UserInfo userInfo = userService.getByMobileAndPassword(username, MD5Util.encode(new String(password)));
        if(userInfo == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        //当然这里也可以对用户名和密码进行校验
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo.getId(), password,getName());
        return info;
    }


}
